package com.wenjunwu.blog.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.druid.util.StringUtils;
import com.wenjunwu.blog.dao.SystemResourceDao;
import com.wenjunwu.blog.dao.SystemRoleDao;
import com.wenjunwu.blog.entity.SystemResource;
import com.wenjunwu.blog.entity.SystemRole;
import com.wenjunwu.blog.service.SystemResourceService;

@Service
public class SystemResourceServiceImpl implements SystemResourceService{

	@Autowired
	private SystemResourceDao systemResourceDao;
	
	@Autowired
	private SystemRoleDao systemRoleDao;

	@Override
	public List<SystemResource> findSystemResource(String roles) {
		String roleName = StringUtils.subString(roles, "_",null);
		SystemRole systemRole = systemRoleDao.selectByRoleName(roleName);
		List<SystemResource> systemResources = systemResourceDao.findResourceByRoleId(systemRole.getId());
		List<SystemResource> navigationList = new ArrayList<SystemResource>();
		// 先找到所有的一级菜单
		for (int i = 0; i < systemResources.size(); i++) {
			// 一级菜单没有Parentid
			if (0 == systemResources.get(i).getParentId()) {
				navigationList.add(systemResources.get(i));
			}
		}
		// 为一级菜单设置子菜单，getChild是递归调用的
		for (SystemResource systemResource : navigationList) {
			systemResource.setNodes(getChild(systemResource.getId(), systemResources));
		}
		return navigationList;
	}

	/**
	 * 递归查找子菜单
	 * @param id 当前菜单id
	 * @param rootMenu 要查找的列表
	 * @return
	 */
	private List<SystemResource> getChild(Long id, List<SystemResource> rootMenu) {
		// 子菜单
		List<SystemResource> childList = new ArrayList<>();
		for (SystemResource systemNavigation : rootMenu) {
			// 遍历所有节点，将父菜单id与传过来的id比较
			if (!StringUtils.isEmpty(systemNavigation.getParentId().toString())) {
				if (systemNavigation.getParentId() == id) {
					childList.add(systemNavigation);
				}
			}
		}
		// 把子菜单的子菜单再循环一遍
		for (SystemResource systemNavigation : childList) {// 没有url子菜单还有子菜单
			if (!StringUtils.isEmpty(systemNavigation.getHref())) {
				// 递归
				systemNavigation.setNodes(getChild(systemNavigation.getId(), rootMenu));
			}
		} // 递归退出条件
		if (childList.size() == 0) {
			return null;
		}
		return childList;
	}
}
